from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone

from article.models import Article


class Comment(models.Model):
    """ 评论 """
    # 作者外键
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    # 文章外键
    article = models.ForeignKey(
        Article,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    # 评论内容
    content = models.TextField()
    # 评论时间
    created = models.DateTimeField(default=timezone.now)
    # 多级评论-评论模型和自身相关联
    parent = models.ForeignKey(
        'self',
        # 数据库该字段可为空
        null=True,
        # 填写表单时该字段可为空
        blank=True,
        #  置空模式,删除时,外键字段被设置为空。前提：null/blank 允许为空
        on_delete=models.SET_NULL,
        # related_name是ForeignKey外键桥梁，用来反向查询
        related_name='children'
    )

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.content[:20]